package cn.dankal.flyaudio.current.post;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import androidx.annotation.RestrictTo;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.facebook.stetho.common.LogUtil;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.vincent.videocompressor.VideoCompress;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import api.CurrentServiceFactory;
import butterknife.BindView;
import butterknife.OnClick;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.common.camera.CamerImageBean;
import cn.dankal.basiclib.common.qiniu.UploadListener;
import cn.dankal.basiclib.common.share.mob.ShareDialog2;
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer;
import cn.dankal.basiclib.common.upload.ali.ImageUpLoadListen;
import cn.dankal.basiclib.protocol.MainProtocol;
import cn.dankal.basiclib.rx.AbstractDialogSubscriber;
import cn.dankal.basiclib.util.CheckApkExist;
import cn.dankal.basiclib.util.ImagePathUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.UriUtils;
import cn.dankal.basiclib.widget.TipDialog;
import cn.dankal.business.pojo.CurrentSendBean;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.oss.view.AliUploadActivity;
import me.jessyan.progressmanager.ProgressListener;
import me.jessyan.progressmanager.ProgressManager;
import me.jessyan.progressmanager.body.ProgressInfo;

/**
 * @author vane
 * @since 2018/8/8
 */
@Route(path = MainProtocol.PUBLISH)
public class PublishActivity extends AliUploadActivity implements WbShareCallback {

    @BindView(R.id.et_feedback)
    EditText etFeedback;
    String content;

    private WbShareHandler shareHandler;

    private boolean isCloseActivity = false;

    private VideoCompress.VideoCompressTask task;

    @Override
    protected void onStart() {
        super.onStart();
        if (isCloseActivity) {
            finish();
        }
    }

    private ShareDialog2 shareDialog2;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish;
    }

    @OnClick(R.id.tv_cancel)
    public void onCancelClicked() {
        finish();
    }

    @OnClick(R.id.tv_action)
    public void onViewClicked() {
        content = etFeedback.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToast("请完善内容..");
            return;
        }
        showLoadingDialog();
        loadingDialog.setCancelable(true);
        loadingDialog.setContent("准备上传");
        loadingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (task != null) {
                    task.cancel(true);
                }
            }
        });

        if (elements != null && elements.size() > 0) {
            for (Uri element : elements) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(element,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String mPicturePath;
                if (columnIndex == -1) {
                    mPicturePath = CamerImageBean.getInstance().getImagePath();
                } else {
                    mPicturePath = cursor.getString(columnIndex);
                }

                cursor.close();
                //  String mPicturePath = UriUtils.getPath(this, Uri.parse(ImagePathUtil.getImageAbsolutePath(this, element)));
                Log.d("PickPicture", mPicturePath);

                int index = mPicturePath.indexOf(".");
                if (index != -1) {
                    suffix = mPicturePath.substring(index, mPicturePath.length());
                }

                if (suffix.equals(".mp4")) {
                    String destPath = "/storage/emulated/0/DCIM/Camera" + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";

                    MediaPlayer mediaPlayer = new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(mPicturePath);
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("视屏获取失败，请重试！");
                        e.printStackTrace();
                    }
                    int time = mediaPlayer.getDuration();
                    if (time > 60 * 1000) {
                        ToastUtils.showShort("视屏时长不能超过一分钟");
                        dismissLoadingDialog();
                        return;
                    }
                    try {
                        if (FormetFileSize(getFileSize(new File(mPicturePath))) > 6.0) {//文件大于6MB才开始压缩
                            task = VideoCompress.compressVideoLow(mPicturePath, destPath, new VideoCompress.CompressListener() {
                                @Override
                                public void onStart() {
                                    loadingDialog.setContent("正在压缩");
                                }

                                @Override
                                public void onSuccess() {
                                    loadingDialog.setContent("正在上传");
                                    String objectName = "fg_" + DKUserManager.getUserInfo().getId() + "_" + System.currentTimeMillis() + suffix;
                                    finalKeys.add(objectName);
                                    mService.asyncPutData(objectName, destPath);
                                }

                                @Override
                                public void onFail() {
                                    runOnUiThread(() -> {
                                        loadingDialog.dismiss();
                                        loadingDialog.setCancelable(true);
                                    });
                                }

                                @Override
                                public void onProgress(float percent) {
                                    runOnUiThread(() -> {
                                        loadingDialog.setContent(Math.ceil(percent) + "%");
                                    });
                                }
                            });
                        } else {
                            String objectName = "fg_" + DKUserManager.getUserInfo().getId() + "_" + System.currentTimeMillis() + suffix;
                            finalKeys.add(objectName);
                            mService.asyncPutData(objectName, mPicturePath);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        dismissLoadingDialog();
                        ToastUtils.showShort("视屏获取失败，请重试！");
                    }
                } else {
                    String objectName = "fg_" + DKUserManager.getUserInfo().getId() + "_" + System.currentTimeMillis() + suffix;
                    finalKeys.add(objectName);
                    loadingDialog.setContent("正在上传...");
                    mService.asyncPutData(objectName, mPicturePath, new ImageUpLoadListen() {
                        @Override
                        public void onSucess(String filepath, String key) {
                        }

                        @Override
                        public void onUpload(String message) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadingDialog.setContent(message);
                                }
                            });
                        }

                        @Override
                        public void onError(String string) {
                        }
                    });
                }
            }

        } else {
            submit(content);
        }

    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            ToastUtils.showShort("文件读取失败！");
        }
        return size;
    }

    /**
     * 转换成MB
     *
     * @param fileS
     * @return
     */
    private double FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
        return fileSizeLong;
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    @Override
    protected void initComponents() {
        super.initComponents();
        shareHandler = new WbShareHandler(this);
        WbSdk.install(this, new AuthInfo(this, "2565652336", "http://open.weibo.com/apps/2565652336/privilege/oauth",
                "all"));
    }

    @Override
    public void addPhoto() {
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "cn.dankal.flyaudio.provider.download"))
                .maxSelectablePerMediaType(9 - elements.size(), 1)
//                      .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                      .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(REQUEST_CODE_CHOOSE);
    }


    @Override
    public void uploadComplete() {
        submit(content);
    }

    public void shareMessage() {
        shareHandler.registerApp();
        WeiboMultiMessage weiboMultiMessage = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        textObject.text = content;
        weiboMultiMessage.textObject = textObject;
        shareHandler.shareMessage(weiboMultiMessage, false);
    }

    private void submit(String content) {

        String[] keys = new String[finalKeys.size()];
        finalKeys.toArray(keys);

        CurrentServiceFactory.release_user_info(new HashMap<String, Object>(3) {{
            put("content", content);
            put("picturesList", finalKeys);
            put("type", type);
        }}).subscribe(new AbstractDialogSubscriber<CurrentSendBean>(this) {
            @Override
            public void onNext(CurrentSendBean reasonBean) {
                showToast("发布成功");
                shareDialog2 = new ShareDialog2(PublishActivity.this, content, reasonBean.uuid, () -> finish());
                shareDialog2.show();
                isCloseActivity = true;
                shareDialog2.setShareMessage(type1 -> {
                    if (CheckApkExist.checkweboExist(PublishActivity.this)) {
                        shareMessage();
                    } else {//未安装微博
                        ToastUtils.showShort("抱歉，您还未安装微博，暂不能分享！");
                    }
                });

                shareDialog2.setOnDismissListener(dialog -> {
                    finish();
                });
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (shareHandler != null) {
            shareHandler.doResultIntent(intent, this);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (shareDialog2 != null) {
            shareDialog2.releaseMemory();
            shareDialog2 = null;
        }
        CheckApkExist.releaseMemory();
    }

    @Override
    public void onWbShareSuccess() {
        ToastUtils.showShort("分享成功！");
    }

    @Override
    public void onWbShareCancel() {
        ToastUtils.showShort("分享取消！");
    }

    @Override
    public void onWbShareFail() {
        ToastUtils.showShort("分享失败！");
    }
}
